To improve the accuracy of Centroid Localization (CL) algorithm in Wireless Sensor Network (WSN), an Optimal Beacon nodes-based Centroid Localization (OBCL) algorithm was proposed. In this algorithm, four mobile beacon nodes were used. First, the path for each mobile beacon node was planned. Second, the optimal beacon nodes were selected from the candidate beacon nodes by each unknown node to estimate location according to Set Deviation Degree (SDD). Besides, a role-change mechanism that an unknown node can assist other unknown nodes to locate as the expectant beacon node after it got its estimated location was adopted to solve the problem of beacon nodes' shortage. At last, to ensure that each unknown node could get its location, a relocation procedure was executed after the completion of the initial locating. The simulation results show that, the average locating error is respectively reduced by 67.7%, 39.2%, 24.4% comparing with the CL, WCL (Weighted Centroid Localization), RR-WCL (Weighted Centroid Localization based on Received signal strength indication Ration) algorithms. For the reason that OBCL can achieve better locating results using only four mobile beacon nodes, it is suitable for scenes which require low network cost and high locating accuracy.